// gateway.cpp : Defines the entry point for the console application.
//

#include "stdafx.h"
#include "Gateway.h"

#ifdef _MSC_VER
BOOL WINAPI ConsoleHandlerRoutine(DWORD dwCtrlType)
{
    g_pGateway->Quit();
    return true;
}

void SetConsoleInfo()
{
    HANDLE      hConsole    = GetStdHandle(STD_OUTPUT_HANDLE);
    COORD       BufferSize  = {108, 320};
    SMALL_RECT  WinRect     = {0, 0, BufferSize.X - 1, 27};

    SetConsoleScreenBufferSize(hConsole, BufferSize);
    SetConsoleWindowInfo(hConsole, true, &WinRect);

#ifdef _DEBUG
    SetConsoleTextAttribute(hConsole, FOREGROUND_GREEN);
#else
    SetConsoleTextAttribute(hConsole, FOREGROUND_GREEN | FOREGROUND_INTENSITY);
#endif

    SetConsoleCtrlHandler(&ConsoleHandlerRoutine, true);
}
#endif

int main(int argc, char* argv[])
{
    BOOL            bRetCode            = false;
    int             nRetCode            = false;
    uint32_t uStateArray[WELL_RAND_STATE_COUNT];

#ifdef _MSC_VER
    SetConsoleInfo();
#endif

#ifdef __linux
    if (!g_pGatewayConfig->m_bForeground)
    {
        nRetCode = fork();
        XY_FAILED_JUMP(nRetCode == 0); 

        setsid();
    }
#endif

    bRetCode = LogOpen("gateway", 65536);
    XYLOG_FAILED_JUMP(bRetCode);

    XY_SetRandSeed((uint32_t)time(NULL));

    for (int i = 0; i < _countof(uStateArray); ++i)
        uStateArray[i] = XY_Rand();

    WellSetRandSeed(uStateArray);

    Log(eLogInfo, "%s", "Gateway server build at " __TIME__ " " __DATE__);

    g_pGateway = new XGateway;

    bRetCode = g_pGateway->Setup();
    XYLOG_FAILED_JUMP(bRetCode);

    Log(eLogInfo, "Gateway server startup ... ... [OK]");

#ifdef _MSC_VER
    Log(eLogInfo, "Press [Ctrl + C] to exit !");
#endif

#ifdef __linux
    signal(SIGINT, OnQuitSignal);
    signal(SIGQUIT, OnQuitSignal);
    signal(SIGTERM, OnQuitSignal); 

    if (!g_pGatewayConfig->m_bForeground)
    {
        bRetCode = SetDaemon();
        XYLOG_FAILED_JUMP(bRetCode);
    }
#endif
    g_pGateway->Run();

    Log(eLogInfo, "Gateway exit !");

Exit0:
    // XY_DELETE(g_pGateway);
    // XY_DELETE(g_pGatewayConfig);
    LogClose();

	return 0;
}

